package com.ssh.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ssh.model.User;
import com.ssh.service.IUserService;

@Controller
@SessionAttributes("loginUser")
public class AccessController {
	
private IUserService userService;
	
	public IUserService getUserService() {
		return userService;
	}
	
	@Inject
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping(value={"/login"},method=RequestMethod.GET)
	public String login(){
		return "access/login";
	}
	
	@RequestMapping(value={"/index"},method=RequestMethod.GET)
	public String index(HttpSession session){
		User u = (User) session.getAttribute("loginUser");
		if(u == null) return "redirect:/login";
		return "index";
	}
	
	@RequestMapping(value={"/login"},method=RequestMethod.POST)
	public String login(String name,String password,Model model){
		User u = userService.login(name, password);
		if(u==null){
			return "redirect:/login";
		}else{
			model.addAttribute("loginUser", u);
			return "redirect:/index";
		}
	}
	
	@RequestMapping(value={"/logout"},method=RequestMethod.GET)
	public String logout(HttpSession session, Model model){
		model.asMap().remove("loginUser");
		session.invalidate();
		return "redirect:/login";
	}
}
